package com.cw.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSONObject;
import com.cw.pojo.TbUser;
import com.cw.service.CartService;
import com.cw.util.CookieUtils;
import com.cw.vo.Cart;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Controller
public class CartController {

    @Reference(check = false)
    private CartService cartService;

    @RequestMapping("addCart")
    @ResponseBody
    public String addCart(HttpServletRequest request, HttpServletResponse response,Long itemId, Integer num){
        //未登录
        //1.从cookie查询购物车数据
        List<Cart> cartList = getCart(request,response);
        TbUser user = (TbUser) SecurityUtils.getSubject().getPrincipal();
        //2.保存购物车
        cartList = cartService.addCart(cartList,itemId,num);
        if (user == null){
            //3.重新返回到cookie中
            CookieUtils.setCookie(request,response,"cartList",JSONObject.toJSONString(cartList),true);
        }else {
            cartService.addCarToRedis(cartList,user.getUsername());
        }

        return "add cart Ok";
    }

    @RequestMapping("getCart")
    @ResponseBody
    public List<Cart> getCart(HttpServletRequest request,HttpServletResponse response){

        TbUser user = (TbUser) SecurityUtils.getSubject().getPrincipal();
        //从cookie中获取购物车数据
        String cartList = CookieUtils.getCookieValue(request, "cartList", true);
        //判断kookie中是否为空值
        if (StringUtils.isBlank(cartList)){
            cartList = "[]";
        }
        //转成对象
        List<Cart> cartListCookie = JSONObject.parseArray(cartList, Cart.class);
        if (user == null){

            return cartListCookie;
        }else{
            List<Cart> cartListFromRedis = cartService.findCartListFormRedis(user.getUsername());
            if (cartListCookie.size() > 0){
                //合并购物车
                List<Cart> cartListMerage  = cartService.merageCart(cartListFromRedis, cartListCookie);
                //将合并过后的购物车重新存到redis中
                cartService.addCarToRedis(cartListMerage,user.getUsername());
                //删除cookie
                CookieUtils.deleteCookie(request,response,"cartList");
                return cartListMerage;
            }

            return cartListFromRedis;
        }



    }



}
